package cn.yunhe.listener;

import cn.yunhe.entity.Admin;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.*;
import java.util.HashSet;
import java.util.Set;

public class UserListener implements HttpSessionAttributeListener, HttpSessionListener, ServletContextListener {
    ServletContext application;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //tomcat启动时,创建容器
        application = sce.getServletContext();
        Set<Admin> adminSet = new HashSet<>();
        application.setAttribute("adminSet", adminSet);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent hsb) {
        //用户登陆时,将用户存入容器中
        HttpSession session = hsb.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        Set<Admin> adminSet = (Set<Admin>) application.getAttribute("adminSet");
        adminSet.add(admin);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent hsb) {
        //用户注销时移除容器中的用户
        Admin admin = (Admin) hsb.getValue();

        System.out.println(admin.getUname());
        System.out.println("-----------"+admin);

        Set<Admin> adminSet = (Set<Admin>) application.getAttribute("adminSet");

        for (Admin a:adminSet) {
            if (a.getUname().equals(admin.getUname())){
                adminSet.remove(a);
            }
        }

        System.out.println(adminSet);

        for (Admin a:adminSet) {
            System.out.println("========"+a.getUname());
            System.out.println("********"+a);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent hsb) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent hse) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
        HttpSession session = hse.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        Set<Admin> adminSet = (Set<Admin>) application.getAttribute("admin");
        adminSet.remove(admin);
        //System.out.println("bbbbbb");
    }
}
